package com.open.system.controller;

import java.util.ArrayList;	
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.open.system.domain.LoanAlipayCreditDO;
import com.open.system.domain.LoanAlipayDO;
import com.open.system.domain.LoanApplyDO;
import com.open.system.domain.rsp.AlipayBank_cards;
import com.open.system.domain.rsp.AlipayBasic;
import com.open.system.domain.rsp.AlipayCunjinbao;
import com.open.system.domain.rsp.AlipayDelivery_addresses;
import com.open.system.domain.rsp.AlipayHuabei;
import com.open.system.domain.rsp.AlipayTransactions;
import com.open.system.domain.rsp.AlipayYuebao;
import com.open.system.domain.rsp.AlipayZhaocaibao;
import com.open.system.service.LoanAlipayCreditService;
import com.open.system.service.LoanAlipayService;
import com.open.system.service.LoanApplyService;

import net.sf.json.JSONArray;

import com.alibaba.fastjson.JSONObject;
import com.open.common.utils.PageUtils;
import com.open.common.utils.Query;
import com.open.common.utils.R;
import com.open.loan.utils.HttpUtil;

/**
 * 
 * 
 * @author aaa
 * @email aaax
 * @date 2019-01-20 14:48:48
 */
 
@Controller
@RequestMapping("/system/loanAlipay")
public class LoanAlipayController {
	@Autowired
	private LoanAlipayService loanAlipayService;
	
	@Autowired
	private LoanApplyService loanApplyService;
	
	@Autowired
	private LoanAlipayCreditService loanAlipayCreditService;
	
	public static String client_secret = "a0d730a9ebb4411f881b52f5e6d5361a";
	public static String access_token = "6aa02e8304cc4ed0abe34b111bf5354f";
	
	@GetMapping()
	@RequiresPermissions("system:loanAlipay:loanAlipay")
	String LoanAlipay(){
	    return "system/loanAlipay/loanAlipay";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("system:loanAlipay:loanAlipay")
	public PageUtils list(@RequestParam Map<String, Object> params){
		//查询列表数据
        Query query = new Query(params);
		List<LoanAlipayDO> loanAlipayList = loanAlipayService.listNew(query);
		int total = loanAlipayService.count(query);
		PageUtils pageUtils = new PageUtils(loanAlipayList, total);
		return pageUtils;
	}
	
	@GetMapping("/add")
	@RequiresPermissions("system:loanAlipay:add")
	String add(){
	    return "system/loanAlipay/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("system:loanAlipay:edit")
	String edit(@PathVariable("id") Long id,Model model){
		LoanAlipayDO loanAlipay = loanAlipayService.get(id);
		model.addAttribute("loanAlipay", loanAlipay);
	    return "system/loanAlipay/edit";
	}
	
	
	@GetMapping("/alipayInfo/{alipayId}")
	@RequiresPermissions("system:loanAlipay:edit")
	String alipayInfo(@PathVariable("alipayId") Long alipayId,Model model){
		Map<String,Object>map=new HashMap<String,Object>();
		map.put("alipayId",alipayId);
		List<LoanAlipayDO>list=loanAlipayService.list(map);
		if(list!=null && list.size()>0){
			LoanAlipayDO alipay=list.get(0);
			
			model.addAttribute("realName",alipay.getRealName());
			
			JSONArray jsonMax = JSONArray.fromObject(alipay.getRemark3());
			for (int z = 0; z <1; z++) {
				net.sf.json.JSONObject jsonObject = jsonMax.getJSONObject(z);
				//=========================
				String cunjinbao=String.valueOf(jsonObject.get("cunjinbao"));
				AlipayCunjinbao alipayCunjinbao=new AlipayCunjinbao();
				if(StringUtils.isNotEmpty(cunjinbao)){
					JSONObject json1 =JSONObject.parseObject(cunjinbao);
					alipayCunjinbao.setHistorical_gram(String.valueOf(json1.get("historical_gram")));
					alipayCunjinbao.setTotal_amount(String.valueOf(json1.get("total_amount")));
					alipayCunjinbao.setTotal_gram(String.valueOf(json1.get("total_gram")));
					alipayCunjinbao.setWait_buy_amount(String.valueOf(json1.get("wait_buy_amount")));
					alipayCunjinbao.setWait_sell_gram(String.valueOf(json1.get("wait_sell_gram")));
					alipayCunjinbao.setYesterday_gram(String.valueOf(json1.get("yesterday_gram")));
				}
				model.addAttribute("alipayCunjinbao",alipayCunjinbao);
				//========================
				String zhaocaibao=String.valueOf(jsonObject.get("zhaocaibao"));
				AlipayZhaocaibao alipayZhaocaibao=new AlipayZhaocaibao();
				if(StringUtils.isNotEmpty(zhaocaibao)){
					JSONObject json1 =JSONObject.parseObject(zhaocaibao);
					alipayZhaocaibao.setHistorical_earnings(String.valueOf(json1.get("historical_earnings")));
					alipayZhaocaibao.setTotal_amount(String.valueOf(json1.get("total_amount")));
					alipayZhaocaibao.setYesterday_earnings(String.valueOf(json1.get("yesterday_earnings")));
				}
				model.addAttribute("alipayZhaocaibao",alipayZhaocaibao);
				//========================
				String delivery_addresses=String.valueOf(jsonObject.get("delivery_addresses"));//集合
				List<AlipayDelivery_addresses>deliveryLists=new ArrayList<AlipayDelivery_addresses>();
				if(StringUtils.isNotEmpty(delivery_addresses)){
					JSONArray jsonArray = JSONArray.fromObject(delivery_addresses);
					for (int i = 0; i < jsonArray.size(); i++) {
						AlipayDelivery_addresses delivery=new AlipayDelivery_addresses();
						net.sf.json.JSONObject newJson = jsonArray.getJSONObject(i);
						delivery.setAddress(String.valueOf(newJson.get("address")));
						delivery.setArea(String.valueOf(newJson.get("area")));
						delivery.setArea_code(String.valueOf(newJson.get("area_code")));
						delivery.setCity(String.valueOf(newJson.get("city")));
						delivery.setCounty(String.valueOf(newJson.get("county")));
						delivery.setName(String.valueOf(newJson.get("name")));
						delivery.setPhone(String.valueOf(newJson.get("phone")));
						delivery.setPost_code(String.valueOf(newJson.get("post_code")));
						delivery.setProvince(String.valueOf(newJson.get("province")));
						deliveryLists.add(delivery);
					}
				}
				model.addAttribute("deliveryLists",deliveryLists);
				//========================
				String transaction=String.valueOf(jsonObject.get("transactions"));//集合
				List<AlipayTransactions>transactions=new ArrayList<AlipayTransactions>();
				if(StringUtils.isNotEmpty(transaction)){
					JSONArray jsonArray = JSONArray.fromObject(transaction);
					for (int i = 0; i < jsonArray.size(); i++) {
						AlipayTransactions alipayTransaction=new AlipayTransactions();
						net.sf.json.JSONObject newJson = jsonArray.getJSONObject(i);
						alipayTransaction.setFund_status(String.valueOf(newJson.get("fund_status")));
						alipayTransaction.setOrder_id(String.valueOf(newJson.get("order_id")));
						alipayTransaction.setPay_direction(String.valueOf(newJson.get("pay_direction")));
						alipayTransaction.setProduct_name(String.valueOf(newJson.get("product_name")));
						alipayTransaction.setRefund_amount(String.valueOf(newJson.get("refund_amount")));
						alipayTransaction.setRemarks(String.valueOf(newJson.get("remarks")));
						alipayTransaction.setService_fee(String.valueOf(newJson.get("service_fee")));
						alipayTransaction.setTransaction_amount(String.valueOf(newJson.get("transaction_amount")));
						alipayTransaction.setTransaction_counterparty(String.valueOf(newJson.get("transaction_counterparty")));
						alipayTransaction.setTransaction_create_time(String.valueOf(newJson.get("transaction_create_time")));
						alipayTransaction.setTransaction_done_time(String.valueOf(newJson.get("transaction_done_time")));
						alipayTransaction.setTransaction_edit_time(String.valueOf(newJson.get("transaction_edit_time")));
						alipayTransaction.setTransaction_from(String.valueOf(newJson.get("transaction_from")));
						alipayTransaction.setTransaction_id(String.valueOf(newJson.get("transaction_id")));
						alipayTransaction.setTransaction_note(String.valueOf(newJson.get("transaction_note")));
						alipayTransaction.setTransaction_status(String.valueOf(newJson.get("transaction_status")));
						alipayTransaction.setTransaction_type(String.valueOf(newJson.get("transaction_type")));
						transactions.add(alipayTransaction);
					}
				}
				model.addAttribute("transactions",transactions);
				//========================
				String bank_cards=String.valueOf(jsonObject.get("bank_cards"));//集合
				List<AlipayBank_cards>alipayBank_cards=new ArrayList<AlipayBank_cards>();
				if(StringUtils.isNotEmpty(bank_cards)){
					JSONArray jsonArray = JSONArray.fromObject(bank_cards);
					for (int i = 0; i < jsonArray.size(); i++) {
						AlipayBank_cards bank_card=new AlipayBank_cards();
						net.sf.json.JSONObject newJson = jsonArray.getJSONObject(i);
						bank_card.setBank_name(String.valueOf(newJson.get("bank_name")));
						bank_card.setBind_time(String.valueOf(newJson.get("bind_time")));
						bank_card.setCard_number(String.valueOf(newJson.get("card_number")));
						bank_card.setCard_type(String.valueOf(newJson.get("card_type")));
						bank_card.setCellphone(String.valueOf(newJson.get("cellphone")));
						bank_card.setFast_pay(String.valueOf(newJson.get("fast_pay")));
						bank_card.setName(String.valueOf(newJson.get("name")));
						alipayBank_cards.add(bank_card);
					}
				}
				model.addAttribute("bankCards",alipayBank_cards);
				//========================
				String huabei=String.valueOf(jsonObject.get("huabei"));
				AlipayHuabei alipayHuabei=new AlipayHuabei();
				if(StringUtils.isNotEmpty(huabei)){
					JSONObject json1 =JSONObject.parseObject(huabei);
					alipayHuabei.setAvailable_line(String.valueOf(json1.get("available_line")));
					alipayHuabei.setCredit_line(String.valueOf(json1.get("credit_line")));
					alipayHuabei.setCurrent_bill(String.valueOf(json1.get("current_bill")));
				}
				model.addAttribute("alipayHuabei",alipayHuabei);
				//========================
				String basic=String.valueOf(jsonObject.get("basic"));
				AlipayBasic alipayBasic=new AlipayBasic();
				if(StringUtils.isNotEmpty(basic)){
					JSONObject json1 =JSONObject.parseObject(basic);
					alipayBasic.setAccount_balance(String.valueOf(json1.get("account_balance")));
					alipayBasic.setAlipay_id(String.valueOf(json1.get("alipay_id")));
					alipayBasic.setCellphone(String.valueOf(json1.get("cellphone")));
					alipayBasic.setEmail(String.valueOf(json1.get("email")));
					alipayBasic.setGender(String.valueOf(json1.get("gender")));
					alipayBasic.setId_card_num(String.valueOf(json1.get("id_card_num")));
					alipayBasic.setPersonal_name(String.valueOf(json1.get("personal_name")));
					alipayBasic.setRealname_authentication(String.valueOf(json1.get("realname_authentication")));
					alipayBasic.setRegister_time(String.valueOf(json1.get("register_time")));
					alipayBasic.setTaobao_id(String.valueOf(json1.get("taobao_id")));
				}
				model.addAttribute("alipayBasic",alipayBasic);
				//========================
				String yuebao=String.valueOf(jsonObject.get("yuebao"));
				AlipayYuebao alipayYuebao=new AlipayYuebao();
				if(StringUtils.isNotEmpty(yuebao)){
					JSONObject json1 =JSONObject.parseObject(yuebao);
					alipayYuebao.setAvailable_amount(String.valueOf(json1.get("available_amount")));
					alipayYuebao.setHistorical_earnings(String.valueOf(json1.get("historical_earnings")));
					alipayYuebao.setTotal_amount(String.valueOf(json1.get("total_amount")));
					alipayYuebao.setUnavailable_amount(String.valueOf(json1.get("unavailable_amount")));
					alipayYuebao.setYesterday_earnings(String.valueOf(json1.get("yesterday_earnings")));
				}
				model.addAttribute("alipayYuebao",alipayYuebao);
			}
			//========================
		}
	    return "system/loanAlipay/alipayInfo";
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("system:loanAlipay:add")
	public R save( LoanAlipayDO loanAlipay){
		if(loanAlipayService.save(loanAlipay)>0){
			return R.ok();
		}
		return R.error();
	}
	/**
	 * 修改
	 */
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("system:loanAlipay:edit")
	public R update( LoanAlipayDO loanAlipay){
		loanAlipayService.update(loanAlipay);
		return R.ok();
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("system:loanAlipay:remove")
	public R remove( Long id){
		
		LoanAlipayCreditDO alipayCreditDO=loanAlipayCreditService.get(id);
		if(alipayCreditDO==null){
			return R.error("不存在认证记录");
		}
		String url="https://www.juxinli.com/api/v1/access_alipay_raw_data_by_token";
		Map<String,String>map=new HashMap<String,String>();
		map.put("client_secret",client_secret);
		map.put("access_token",access_token);
		map.put("token",alipayCreditDO.getAlipayRemark1());
		String returnJson=HttpUtil.sendGet(url,map);
		System.out.println(returnJson);
		JSONObject jsonObject =JSONObject.parseObject(returnJson);
		String msg=jsonObject.getString("note");
		if("30019".equals(jsonObject.getString("code"))){
			System.out.println(msg);
			String data=jsonObject.getString("data");
			LoanAlipayDO alipayDO=new LoanAlipayDO();
			alipayDO.setAlipayId(id);
			alipayDO.setUserId(alipayCreditDO.getUserId());
			alipayDO.setRealName(alipayCreditDO.getRealName());
			alipayDO.setRemark1("1");
			alipayDO.setRemark2(alipayCreditDO.getAlipayRemark7());
			alipayDO.setRemark3(data);
			if(loanAlipayService.save(alipayDO)>0){
				Map<String,Object>mapApply=new HashMap<String,Object>();
				mapApply.put("userId", alipayCreditDO.getUserId());
				List<LoanApplyDO>applyDOs=loanApplyService.list(mapApply);
				if(applyDOs!=null && applyDOs.size()>0){
					LoanApplyDO apply=applyDOs.get(0);
					apply.setBillingtype("2");
					loanApplyService.update(apply);
				}
				return R.ok();
			}
			return R.error();
		}else if ("10001".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("参数client_secret不能为空");
			return R.error("参数client_secret不能为空");
		}else if ("10005".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("机构授权access_token不能为空");
			return R.error("机构授权access_token不能为空");
		}else if ("10015".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("请输入采集流程token");
			return R.error("请输入采集流程token");
		}else if ("20002".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("机构不存在");
			return R.error("机构不存在");
		}else if ("20003".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("账号已冻结，调用失败");
			return R.error("账号已冻结，调用失败");
		}else if ("20007".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("身份验证失败");
			return R.error("身份验证失败");
		}else if ("20014".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("获取用户采集信息失败，请检查token是否正确");
			return R.error("获取用户采集信息失败，请检查token是否正确");
		}else if ("20041".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("access_token已失效");
			return R.error("access_token已失效");
		}else if ("20048".equals(jsonObject.getString("code"))) {
			System.out.println(msg);
			System.out.println("获取支付宝原始数据失败");
			return R.error("获取支付宝原始数据失败");
		}
		return null;
	}
	
	/**
	 * 删除
	 */
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("system:loanAlipay:batchRemove")
	public R remove(@RequestParam("ids[]") Long[] ids){
		loanAlipayService.batchRemove(ids);
		return R.ok();
	}
	
}
